import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Error from '../views/Error.vue'
// import { component } from 'vue/types/umd'

/* import Dorm from '../views/Dorm.vue'
import Student from '../views/Student.vue'
import NoticeHome from '../views/NoticeHome.vue'
import Admin from '../views/Admin.vue'
import Notice from '../views/Notice.vue' */

Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    // name: "Login",
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    component:Home,
    // 重定向，默认显示页面
    redirect:"/home/noticeHome",
    // 富文本页面
    children:[
      {
        path:'/home/edit',
        component:() => import ('../views/Edit.vue')
      },
      {
        path:'/home/highCharts',
        component:() => import ('../views/Highcharts.vue')
      },
      {
        path:'/home/eCharts',
        component:() => import ('../views/Echarts.vue')
      },
    ]
  /*   children:[
      {
        path:'/home/noticeHome',
        component:() => import ('../views/NoticeHome.vue')
      },
      {
        path:'/home/student',
        component:() => import ('../views/Student.vue')
      },
      {
        path:'/home/dorm',
        component:() => import ('../views/Dorm.vue')
      },
      {
        path:'/home/notice',
        component:() => import ('../views/Notice.vue')
      },
      {
        path:'/home/admin',
        component:() => import ('../views/Admin.vue')
      },
    ], */
  },
  // 其它未定义的页面
  {
    path:'*',
    component:Error,
    // redirect:'/login'
  },
]

const router = new VueRouter({
  mode: 'history',
  // mode: 'history',
  // base: process.env.BASE_URL,
  routes
})

// 全局路由守备
// 解决问题：刷新页面到错误页面的问题
router.beforeEach((to, from,next) => {
  // 获取路由组件数量
  // console.log("to:",to)
  // console.log("from:",from)
  // console.log("路由节点",router.getRoutes())
  if(to.path == '/' || to.path == '/login'){
    console.log('去登录页面')
    next()
  }else{
    console.log('去非登录页面')
    let power = sessionStorage.getItem('power')
    if(power){
      // 已经登录
      console.log( '登录成功')
      let routerArr = router.getRoutes()
      if(routerArr.length > 6){
        // 创建过路由
        next()
      }else{
        // 没有创建路由
        console.log('刷新页面')
        // 再次创建动态路由
        JSON.parse(power).forEach((v)=>{
          router.addRoute('Home',{path:v.href,component:() => import (`../views/${v.com}.vue`)})
        })
        // 
        console.log({...to})
        next({...to,replace:true})
      }
    }else{
      // 没有登录
      console.log('没有登录成功')
      next({path:'/',replace:true})
    }
  }
});


export default router
